package com.dk.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //shiro的过滤器工厂类
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        //给shiro的过滤器工厂类设置安全管理器
        factoryBean.setSecurityManager(defaultWebSecurityManager);
        /*
         * anon 表示不需要登录直接放过
         * authc 必须登录才能访问
         * hashMap,LinkedHashMap,treeMap
         * LinkedHashMap:存取有序 应用场景:shiro过滤器
         * treeMap:根据存入元素大小排序
         * */
        Map<String,String> map = new LinkedHashMap<>();//有序的map : 存取有序
        //map.put("/orderInfo/**","authc");//拦截结算相关 只有登录才能结算
        map.put("/**","anon");//放过其它所有
        factoryBean.setFilterChainDefinitionMap(map);
        factoryBean.setLoginUrl("/userLogin/tologin");//拦截后的跳转路径

        //将安全管理器放入到过滤器工厂类中
        factoryBean.setSecurityManager(defaultWebSecurityManager);
        return factoryBean;
    }
    @Bean
    public DefaultWebSecurityManager SecurityManager(@Autowired LoginRealm loginRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(loginRealm);
        return securityManager;

    }
    @Bean
    public LoginRealm LoginRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher){
        LoginRealm loginRealm = new LoginRealm();
        loginRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return loginRealm;
    }
    @Bean
    //配置加密类
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher macher = new HashedCredentialsMatcher();
        //配置加密算法为MD5
        macher.setHashAlgorithmName("MD5");
        //加密3次
        macher.setHashIterations(3);
        //设置加密编码
        macher.setStoredCredentialsHexEncoded(true);
        return macher;
    }
}
